import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
//封装一个函数，用来检测你是否有当前地址的访问权
function hasUrl(path, next) {
  let result = store.state.userinfo.menus_url.find((item) => item == path);
  if (result) {
    next();
  } else {
    next("/home");
  }
}

Vue.use(VueRouter)

export const indexRoutes = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/menu", next)
    },
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/role", next)
    },
  },
  {
    path: '/manger',
    component: () => import('../views/manger/manger.vue'),
    meta: {
      title: '管理员管理'
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/manger", next)
    },
  },
  {
    path: '/cate',
    component: () => import('../views/goodscate/goodscate.vue'),
    meta: {
      title: '商品分类',
    },
  },
  {
    path: '/specs',
    component: () => import('../views/goodsspecs/goodsspecs.vue'),
    meta:{
      title:'商品规格'
    }
  },
  {
    path:'/goods',
    component:() => import('../views/goods/goods.vue'),
    meta:{
      title:'商品管理'
    }
  },
  {
    path:'/banners',
    component:()=>import('../views/banners/banners.vue'),
    meta:{
      title:'轮播图管理'
    }
  },
  {
    path:'/seck',
    component:()=>import('../views/seck/seck.vue'),
    meta:{
      title:'活动管理'
    }
  },
  {
    path:'/member',
    component:()=>import('../views/member/member.vue'),
    meta:{
      title:'会员管理'
    }
  },
]


const routes = [
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue')
      },
      ...indexRoutes,
      {
        path: '',
        redirect: '/home'
      }
    ]
  },
  {
    path: '*',
    redirect: '/index'
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router
//登录拦截事件
router.beforeEach((to,from,next)=>{
  if(to.path == '/login'){
    next();
    return;
  }

  if(store.state.userinfo){
    next();
    return;
  }

  next('/login')
})